/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-05-14 23:16:20
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-05-15 15:49:46
 * @FilePath: \react_nest_demo\nest_service\src\user\user.service.ts
 * @Description: 服务层 - 接口逻辑实现
 */
import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { RegisterUserDto } from './dto/register-user.dto';
import { LoginUserDto } from './dto/login-user.dto';

import { User } from './entities/user.entity';

import { SecreTool, JwtDecrypTool } from '../utils/internalTools';
import { FindUserDto } from './dto/find-user.dto';

@Injectable()
export class UserService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly secreTool: SecreTool,
    private readonly jwtDecrypTool: JwtDecrypTool,
    @InjectRepository(User) private readonly userRepository: Repository<User>,
  ) {}

  // 注册
  async register({ username, password }: RegisterUserDto) {
    // 查找⽤户是否注册过
    const foundUser = await this.userRepository.findOneBy({
      username: username,
    });

    if (foundUser) {
      throw new BadRequestException('⽤户已存在！');
    }

    // 插⼊⼀条新⽤户数据
    const user = await this.userRepository.save({
      username,
      password: this.secreTool.getSecret(password),
      head_img: 'https://sdfsdf.dev/35x35.png',
    });

    return {
      msg: '注册成功！',
      data: this.jwtService.sign({ id: user.id }),
    };
  }

  // 登录
  async login({ username, password }: LoginUserDto) {
    const user = await this.userRepository.findOneBy({ username });

    if (!user) {
      throw new BadRequestException('该账号不存在！');
    }

    const isPasswordValid =
      user.password === this.secreTool.getSecret(password);

    if (!isPasswordValid) {
      throw new BadRequestException('账号或密码错误');
    }

    return {
      msg: '登录成功！',
      data: this.jwtService.sign({ id: user.id }),
    };
  }

  // 查找
  async find(findUserDto: FindUserDto) {
    const id = this.jwtDecrypTool.getDecryp(findUserDto.authorization);

    const user = await this.userRepository.findOne({
      where: { id },
    });

    return {
      id: user.id,
      username: user.username,
      head_img: user.head_img,
    };
  }
}
